package org.xs.web.http.velocity;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.io.VelocityWriter;
import org.xs.web.http.TemplateNotFoundException;

public class TemplateFactory {
	public static final String DEFAULT_ENCODE="UTF-8";
	private VelocityEngine velocityEngine;
	
	protected void megerTemplate(HttpServletResponse response,Template template,Context context) {
		 VelocityWriter vw = null;
		 Writer writer  = null;
		 try {
			 StringWriter swrite = new StringWriter(1024);
			 writer = getResponseWriter(response);
			 vw = new VelocityWriter(swrite, 4 *1024, true);
			 template.merge(context, vw);
			 if(vw != null){
					try {
						vw.flush();
					} catch (IOException e) {
						 throw new VelocityException(e);
					}finally{
						vw.recycle(null);
					}
					 
				}
			swrite.close();
			writer.write(swrite.toString());
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(writer != null){
				try {
					writer.flush();
				} catch (IOException e) {
					 
				}
			}
		}
		
		 
	 }

	public Template getTemplate(String name, String encoding){
    try {
    	if (encoding == null){
			return getVelocityEngine().getTemplate(name);
     }
     else
     {  
			return getVelocityEngine().getTemplate(name, encoding); 
     }
	} catch (Exception e) {
//		throw new VelocityException(e);
		throw new TemplateNotFoundException();
	}
	 
   }

	 
protected Writer getResponseWriter(HttpServletResponse response)
      throws UnsupportedEncodingException, IOException
  {
      Writer writer = null;
      try
      {
          writer = response.getWriter();
      }
      catch (IllegalStateException e)
      {
          
          String encoding = response.getCharacterEncoding();
          if (encoding == null)
          {
              encoding = DEFAULT_ENCODE;
          }
          writer = new OutputStreamWriter(response.getOutputStream(),
                                          encoding);
      }
      return writer;
  }
	  
	private VelocityEngine getVelocityEngine() {
			return velocityEngine;
	}
}
